package com.xinqi.common.third.chat.help;

import com.xinqi.common.third.chat.ChatProperties;
import io.rong.RongCloud;
import io.rong.RongCloudConfig;
import io.rong.methods.chatroom.Chatroom;
import io.rong.methods.conversation.Conversation;
import io.rong.methods.group.Group;
import io.rong.methods.message.Message;
import io.rong.methods.user.User;
import io.rong.models.Result;
import io.rong.models.response.TokenResult;
import io.rong.models.user.UserModel;

import java.util.Objects;
import java.util.Optional;

/**
 * 融云帮助类
 *
 * @author linkai
 * @date 2023/2/22
 */
public class RongyunHelp {
    private static final int SUCCESS = 200;
    private final ChatProperties.Rongyun rongyun;
    private final RongCloud rongCloud;

    public RongyunHelp(ChatProperties chatProperties) {
        this.rongyun = chatProperties.getRongyun();
        this.rongCloud = RongCloud.getInstance(this.rongyun.getKey(), this.rongyun.getSecret());
    }

    public RongCloud client() {
        return this.rongCloud;
    }

    public User user() {
        return this.rongCloud.user;
    }

    public Group group() {
        return this.rongCloud.group;
    }

    public Message message() {
        return this.rongCloud.message;
    }

    public Chatroom chatroom() {
        return this.rongCloud.chatroom;
    }

    public Conversation conversation() {
        return this.rongCloud.conversation;
    }

    public RongCloudConfig config() {
        return this.rongCloud.getConfig();
    }

    public UserModel userModel(String id, String name, String portrait) {
        return userModel(id, name, portrait, null, null, null);
    }

    public UserModel userModel(String id, String name, String portrait, Integer minute, UserModel[] blacklist, UserModel[] whitelist) {
        return new UserModel().setId(id).setName(name).setPortrait(portrait)
            .setMinute(minute).setBlacklist(blacklist).setWhitelist(whitelist);
    }

    public TokenResult register(String id, String name, String portrait) throws Exception {
        return register(id, name, portrait, null, null, null);
    }

    public TokenResult register(String id, String name, String portrait, Integer minute, UserModel[] blacklist, UserModel[] whitelist) throws Exception {
        return user().register(
            userModel(id, name, portrait, minute, blacklist, whitelist)
        );
    }

    public TokenResult register(UserModel user) throws Exception {
        return user().register(user);
    }

    public boolean ok(Result result) {
        return Optional.ofNullable(result)
            .map(v -> Objects.equals(result.getCode(), SUCCESS))
            .orElse(false);
    }
}
